<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: Ringo Chan <334258471@qq.com> <http://www.jxlnxx.com/>
// +----------------------------------------------------------------------

namespace Api\Controller;

/**
 * API商品控制器
 * 主要获取商品数据
 * 
 * @author Ringo Chan <334258471@qq.com>
 */
class ProductController extends ApiController{


    /**
     * 限时抢购/正价商品区 列表
     *
     * @param string category_id 商品分类
     * @param integer page 页码
     * @param integer pagesize 每页数据总数
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getProductList(){

        $page = I('post.page', 1); // 页码
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        $start=0;
        $good_type = I('good_type');
        $top = I('top');
        $product = M('product');
        $map=array();
        $map['status'] = 1;
        $map['is_show'] = 1;
        if($good_type == 1){ //正价商品
            $map['good_type'] =1;
            if($top){
                $limit = 6;
                $map['is_home_show']=1;
            }else{
                $limit = 1000;
            }
        }else if($good_type == 2){ //限时抢购
            $map['good_type'] =2;
            if($top){
                $limit = 3;
                $map['is_home_show']=1;
            }else{
                $limit = 1000;
            }
        }

        if ($page > 0 && $pagesize > 0){
            $start = ($page - 1) * $pagesize;
        }

        $list = $product->limit($limit)->where($map)->field('id,title,y_price,price,quantity,sales,good_type')->order('update_time ASC')->select();

        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');

        foreach ($list as $key => $item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();

            $list[$key]['image'] = get_url($image_info['cover_id'], 'path');
            $list[$key]['total'] = $item['quantity'] + $item['sales'];
            $list[$key]['y_price'] = format_money($item['y_price']);
            $list[$key]['price'] = format_money($item['price']);
        }

        $list === false && response(-9);

        response(1, $list);
    }
    
    /**
     * 获取我的商品列表
     * 
     * @param string type 商品类型
     * @param integer page 页码
     * @param integer pagesize 每页数据总数
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getMyProducts(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        params_exist(array('type'));
    
        $type = I('post.type', 0); // 商品类型
        $page = I('post.page', 1); // 页码
        $pagesize = I('post.pagesize', 10); // 分页显示条数
        $status = I('post.status'); // 商品状态

        if($status !== ''){
            !preg_match('/^0|1$/', $status) && response(-2,'状态值错误');
            $map['status']=$status;
        }
        !get_table_field($type, 'name', 'id', 'product_type') && response(-2, '', '无效商品类型');
        
        $options = array();
        $model = M('product');
        
        
        $map['uid'] = API_UID;
        $map['type'] = $type;
        $map['is_show'] = 1;
        
        $options['where'] = $map;
        $options['field'] = array('id', 'title','sales', 'price', 'quantity','type','status');
        $options['order'] = 'id DESC';

        $OPT = new \ReflectionProperty($model,'options');
        $OPT->setAccessible(true);
        
        $options = array_merge( (array)$OPT->getValue($model), $options );
        $total = $model->where($options['where'])->count();
        
        if ($page > 0 && $pagesize > 0) {
            $start = ($page - 1) * $pagesize;
            $options['limit'] = $start.','.$pagesize;
        }
        
        $model->setProperty('options',$options);

        $list = $model->select();
    
        /* 增加附加属性值：image、discount */
        $M_product_image = M('product_image');
    
        foreach ($list as $key => $item) {
            $image_info = $M_product_image->where(array('product_id'=>$item['id']))->order('id ASC')->find();
    
            $list[$key]['image'] = get_cover($image_info['cover_id'], 'path');
        }
    
        $list === false && response(-9);

        $result = array(
            'total' => $total,
            'result' => $list
        );

        response(1, $result);
    }
    
    /**
     * 商品 上架
     * @param int id
     * 
     */
    public function myproductPutaway(){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
        
        $id = I('post.id', 0);
        
        $M_product = M('product');
        
        $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
        
        $info = $M_product->where($map)->find();
        if($info['quantity']<=0){
            response(-4,'','商品库存不足！');
        }
        //==判断商户积分是否足够商品的积分
      //  $member = M('member')->where('uid='.API_UID)->find();
        $username = M('ucenter_member')->where('id='.API_UID)->getField('username');
        //$coin = M('users','cmf_')->where('user_login='.$username)->getField('coin');
        $score= M('member')->where('uid='.API_UID)->getField('score');
        if($score<$info['score'])
        {
            response(-3,'您的积分不足，商品赠送积分不能上架！');
        }

        empty($info) && response(-2,'商品不存在');
        
        $M_product->where($map) ->setfield('status',1) ? response(1) : response(-9);
    }
    
    /**
     * 商品 下架
     * @param int id
     *
     */
    public function myproductHalt (){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
         $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
    
        $info = $M_product->where($map)->find();
    
        empty($info) && response(-2,'商品不存在');
    
        $M_product->where($map) ->setfield('status',0)  ? response(1) : response(-9);
    }
    
    /**
     * 商品 下架
     * @param int id
     *
     */
    public function myproductDel (){
        !api_login() && response(-94);
        !passed_login() && response(-95);
        !only_login() && response(-96);
    
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
        $map=array('id'=>$id, 'uid'=>API_UID,'is_show'=>1);
    
        $info = $M_product->where($map)->delete();
    
        empty($info) && response(-2,'商品不存在');

        $info? response(1) : response(-9);;
    }
    
    /**
     * 我的商品详情
     *
     * @param integer id 商品编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getMyProduct(){

        params_exist(array('id'));
        $id = I('post.id', 0);
    
        $M_product = M('product');
    
        $info = $M_product->where(array('id'=>$id,'is_show'=>1))->find();
    
        !$info && response(-2, '', '没有找到匹配商品');
        
        $result = array();
    
        switch ($info['type']) {
            case 'putong':
                $M_product_special_panic = M('product_special_panic');
                $info['in_special_panic'] == 1 && $result['special_panic'] = $M_product_special_panic->where(array('product_id'=>$id))->select();
                $fields = array('id', 'uid','score', 'shop_id', 'category_id', 'title', 'description', 'price', 'quantity', 'movie',
                    'security_7days', 'security_delivery', 'in_special_panic', 'in_special_gift',
                    'status','province_id','city_id','area_id','address','sales');
                break;
            case 'paipin':
                $fields = array('id', 'uid', 'shop_id', 'category_id', 'title', 'description', 'price',
                'maxprice', 'quantity', 'movie', 'start_time', 'end_time', 'security_7days',
                'security_delivery',
                'status','province_id','city_id','area_id','address','sales');
                break;
            case 'xianzhi':
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity',
                'movie', 'security_7days', 'security_delivery','status','province_id','city_id',
                'area_id','address','sales');
                break;
            default:
                $fields = array('id', 'uid', 'category_id', 'title', 'description', 'price', 'quantity',
                'movie', 'security_7days', 'security_delivery','status','province_id','city_id','area_id',
                'address','sales','score');
                break;
        }
    
        foreach ($fields as $field){
            $result[$field] = $info[$field];
        }
        
         $result['status_text'] =getStatus('product')[$result['status']];
         $result['address_full']=
         get_table_field($info['province_id'],'province_id','province','hat_province')
         .get_table_field($info['city_id'],'city_id','city','hat_city')
         .get_table_field($info['area_id'],'area_id','area','hat_area')
         .$info['address'] ;
        $result['category_title']=get_table_field($info['category_id'],'id','title','product_category');
        $M_product_image = M('product_image');
        $images = $M_product_image->where(array('product_id'=>$id))->select();
        foreach ($images as $image) {
            $result['images'][] = array(
                'id' => $image['id'],
                'cover_id'=>$image['cover_id'],
                'path' => get_cover($image['cover_id'], 'path')
            );
        }    
        if($info['movie']){
            $result['movie'] = array(
                'thumb_image_path'=>get_url(get_movie($result['movie'],'thumb_cover_id')),
                'id' => $info['movie'],
                'path' => mb_substr($_SERVER["HTTP_REFERER"], 0, strrpos($_SERVER["HTTP_REFERER"], "/")) . '/Uploads/Movie/' . get_movie($result['movie'], 'savepath') . get_movie($result['movie'], 'savename'),
                'mime' => get_movie($result['movie'], 'mime')
            );
        }else{
            $result['movie']=null;
        }
        
        //组合属性
        $M_option=M('product_option');
        $o_names=$M_option->where(array('product_id'=>$id,'pid'=>0))->select()|0;
        foreach ($o_names as &$item){
            $item['_child']=$M_option->where(array('pid'=>$item['id']))->select();
        }
    
        //组合价格
        $M_product_option_price=M('product_option_price');
        $result['option_price']=$M_product_option_price
        ->where(array('product_id'=>$id))->field('product_option_id,price')->select()|$result['price'];
    
        $result['option']=$o_names;
        response(1, $result);
    }
    
    /**
     * 获取出售中商品详情
     * 
     * @param integer id 商品编号
     * @author Ringo Chan <334258471@qq.com>
     */
    public function getProduct(){
        params_exist(array('id'));
        
        $id = I('post.id', 0);
        
        $M_product = M('product');
        
        $info = $M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
        
        !$info && response(-2, '', '没有找到匹配商品');
        
        $M_product->where(array('id'=>$id, 'status'=>1))->setInc('view');

        $result = array(); 
        
        switch ($info['type']) {
            case 'putong':
                $M_product_special_panic = M('product_special_panic');
                $info2=$M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
                $info2['in_special_panic'] == 1 && $result['special_panic'] = $M_product_special_panic->where(array('product_id'=>$id))->select();
                $fields = array('id', 'title', 'description','y_price', 'price', 'quantity','good_type');
                break;
        }

//        $result['identify_price'] = get_table_field($info['category_id'],'product_category_id','price','identify') | 0;
        $info3=$M_product->where(array('id'=>$id, 'status'=>1,'is_show'=>1))->find();
        $province = M('hat_province')->where('province_id='.$info3['province_id'])->getField('province');
        $city  = M('hat_city')->where('city_id='.$info3['city_id'])->getField('city');
        $area = M('area')->where('area_id='.$info3['area_id'])->getField('area');
        $arddress= $province.$city.$area;
        $result['address'] = $arddress;
        foreach ($fields as $field){
            $result[$field] = $info3[$field];
        }

        $result['y_price'] = format_money($result['y_price']);
        $result['price'] = $result['price'];

        $M_product_image = M('product_image');
        $images = $M_product_image->where(array('product_id'=>$id))->select();
        $result['images'] =array();
        foreach ($images as $image) {
            $result['images'][] = array(
                'id' => $image['id'],
                'path' => get_cover($image['cover_id'], 'path')
            );
        }

        //组合属性
        $M_product_option=M('product_option');
        $M_product_option_price=M('product_option_price');
        $map=array('product_id'=>$id);

        $options = $M_product_option->where(array(
            'product_id' => $id,
            'pid' => 0
        ))
            ->field('id,title')
            ->select();

        if ($options) {
            foreach ($options as &$_item) {
                 $child= $M_product_option->where(array(
                    'pid' => $_item['id']
                ))->field('id,title')->select();
                $_item['_child'] =$child?$child:array();
            }
        }
        $options_price=$M_product_option_price->where($map)
            ->field('id,price,product_option_id')->select();

        $result['option']=$options;
        if($options_price){
        /*    foreach ($options_price as &$options){
                $options['price'] =format_money($options['price']);
            }*/
            $result['option_price']=$options_price;
        }else{
            $result['option_price']=array();
        }


        //$result['option']=$o_names;
        response(1, $result);
    }
    
    /**
     * @param int id
     * 获取商品属性价格
     */
    public function getOptionPrice(){
        params_exist(array('id'));
        $id=I('post.id');
        !get_table_field($id,'id','id','product') && response(-2,'','商品不存在');
        $result=M('product_option_price')
        ->where(array('product_id'=>$id))->field('product_option_id,price')->select();
        if($result){
            response(1,$result);
        }else{
            $price=get_table_field($id,'id','price','producdt');
            $price ? response(1,$price) : response(-1);
        }
    }
    
    /**
     * 商品属性
     */
    public function productOption(){
        params_exist(array('product_id'));
        
        $id=I('post.product_id');
        $M_product_option=M('product_option');
        $M_product_option_price=M('product_option_price');
        $map=array('product_id'=>$id);

        $options = $M_product_option->where(array(
            'product_id' => $id,
            'pid' => 0
        ))
            ->field('id,title')
            ->select();

        if ($options) {
            foreach ($options as &$_item) {
                $_item['_child'] = $M_product_option->where(array(
                    'pid' => $_item['id']
                ))
                    ->field('id,title')->select();
            }
        }
        $options_price=$M_product_option_price->where($map)
            ->field('id,price,product_option_id')->select();

        $result['option']=$options;
        $result['option_price']=$options_price;
        
       $options ? response(1,$result) : response(-2);
    }
    
    /**
     * 新增/编辑 商品选项
     *
     * @param integer id 商品选项编号
     * @param integer pid 商品选项父级编号
     * @param string text 商品选项属性值
     * @author Ringo Chan <334258471@qq.com>
     */
    public function editOption($id = 0, $pid = 0, $product_id = 0, $text = ''){
        $M_product = M('product');
        $M_product_option = M('product_option');
    
        if (empty($id) && empty($pid)) {
            empty($product_id) && !$M_product->find($product_id) && response(-1, null, '非法参数');
            empty($text) && response(-1, null, '选项标题不能为空');
    
            $id = $M_product_option->add(array('product_id'=>$product_id, 'pid'=>0, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } elseif (empty($id)) {
            empty($text) && response(-1, null, '属性标题不能为空');
            empty($pid) && response(-1, null, '非法参数');
    
            $info = $M_product_option->find($pid);
            !$info && response(-2, null, '非法参数');
    
            $id = $M_product_option->add(array('product_id'=>$info['product_id'], 'pid'=>$pid, 'title'=>$text, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        } else {
            empty($text) && response(-1, null, '属性标题不能为空');
            !$M_product_option->find($id) && response(-1, null, '非法参数');
    
            $M_product_option->where(array('id'=>$id))->save(array('title'=>$text, 'update_time'=>NOW_TIME));
        }
    
        response(1, array('id'=>$id));
    }
    
    /**
     * 删除 商品选项
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOption($id = 0){
        $M_product_option = M('product_option');
    
        !$M_product_option->find($id) && response(-1, null, '非法参数');
    
        $M_product_option->where(array('id|pid'=>$id))->delete();
    
        response(1);
    }
    
    /**
     * 增加 商品选项价钱
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function addOptionPrice($product_id = 0, $ids = 0, $price = 0){
        $M_product = M('product');
        $M_product_option = M('product_option');
        $M_product_option_price = M('product_option_price');
    
        empty($product_id) && !$M_product->find($product_id) && response(-1, null, '非法参数');
        empty($ids) && response(-1, null, '请选择选项');
        !is_numeric($price) && $price <= 0 && response(-1, null, '价格不能低于1元');
    
        !is_array($ids) && $ids = str2arr($ids);
        // $option_category_count = $M_product_option->where(array('product_id' => $product_id, 'pid'=>0))->count();
        // count($ids) != $option_category_count && response(-1, null, '缺少组合选项');
    
        sort($ids, SORT_NUMERIC);
        $ids = arr2str($ids);
        $info = $M_product_option_price->where(array('product_id'=>$product_id, 'product_option_id'=>$ids))->find();
        $info && response(-2, null, '组合选项已存在');
        $id = $M_product_option_price->add(array('product_id'=>$product_id, 'product_option_id'=>$ids, 'price'=>$price, 'create_time'=>NOW_TIME, 'update_time'=>NOW_TIME));
        $id > 0 ? response(1, array('id'=>$id)) : response(-9);
    }
    
    /**
     * 修改 商品选项价钱
     */
    public function editOptionPrice($id = 0, $price = 0) {
        $M_product_option_price = M('product_option_price');
    
        !$M_product_option_price->find($id) && response(-1, null, '非法参数');
        !is_numeric($price) && $price <= 0 && response(-1, null, '价格不能低于1元');
    
        $boolean = $M_product_option_price->where(array('id'=>$id))->setField(array('price'=>$price, 'update_time'=>NOW_TIME));
        $boolean !== false ? response(1, array('id'=>$id)) : response(-9);
    }
    
    /**
     * 删除 商品选项价钱
     *
     * @author Ringo Chan <334258471@qq.com>
     */
    public function deleteOptionPrice($id = 0){
        $M_product_option_price = M('product_option_price');
        !$M_product_option_price->find($id) && response(-1, null, '非法参数');
        $M_product_option_price->where(array('id'=>$id))->delete();
        response(1);
    }
    
    public function getHots() {
        $productList = M('product')->where(array('is_top'=>array('eq', 1)))->field(array('id', 'type', 'title', 'view', 'price'))->limit(0,5)->select();
        foreach ($productList as &$product) {
            $product['image'] = M('product_image')->where(array('product_id'=>$product['id']))->order('id ASC')->find();
            $product['image'] = get_url($product['image']['cover_id']);
        }
        response(1, $productList);
    }
    
    public function getGroups() {
        $group = I('post.group', 0);
        $filters['group'] = $group;
        $groupList = M('product_group')->where($filters)->order('sort ASC, id DESC')->select();
        foreach ($groupList as &$group) {
            $group['image'] = get_url($group['cover_id']);
        }
        response(1, $groupList);
    }
}
